const { observable, action } = require('mobx-miniprogram');

// 内容管理模块Store
export const contentStore = observable({
  // 富文本内容数据
  formContent: [{
    type: 'text',
    val: '',
  }],
  
  // 当前编辑状态
  isEditing: false,
  
  // Action: 设置内容
  setFormContent: action(function(content) {
    if (Array.isArray(content) && content.length > 0) {
      this.formContent = content;
    }
  }),
  
  // Action: 从编辑器获取内容
  getContentFromEditor: action(function(editor) {
    if (!editor) return [];
    
    try {
      const nodeList = editor.getNodeList();
      if (Array.isArray(nodeList) && nodeList.length > 0) {
        this.setFormContent(nodeList);
      }
      return this.formContent;
    } catch (err) {
      console.error('[MobX ContentStore]从编辑器获取内容失败', err);
      return this.formContent;
    }
  }),
  
  // Action: 设置编辑状态
  setEditingStatus: action(function(status) {
    this.isEditing = status;
  }),
  
  // Action: 获取内容描述
  getContentDesc: action(function() {
    let desc = '';
    if (!this.formContent || this.formContent.length == 0) return desc;
    
    // 从内容中提取文本作为描述
    for (let k = 0; k < this.formContent.length; k++) {
      if (this.formContent[k].type == 'text') {
        desc = this.formContent[k].val;
        if (desc) break;
      }
    }
    
    // 处理描述文本
    desc = desc.replace(/<[^>]+>/g, '');
    desc = desc.replace(/&nbsp;/g, ' ');
    desc = desc.replace(/\s+/g, ' ');
    desc = desc.substr(0, 100).trim();
    
    return desc;
  }),
  
  // Action: 清空内容
  clearContent: action(function() {
    this.formContent = [{
      type: 'text',
      val: '',
    }];
  })
}); 